<template>
	<view class="page">
		<view class="navbar" v-if="list.length>0">
			{{current+1}}/{{list.length}}
		</view>
		<view class="content">
			<view class="swiper" v-if="list.length>0">
				<swiper class="swiper-box" :current="current" @change="changeCurrent">
					<block v-for="(item,j) in list" :key="j">
						<!-- 中文选词 -->
						<swiper-item class="swiper-list" v-if="item.type==3">
							<view class="swiper-item">
								<view class="question">
									<view class="t t1" >{{item.translation[0].wordSex}}  {{item.translation[0].chinExplain}}</view>
								</view>
								<view class="answer">
									<block v-for="(an,index) in item.wordList" :key="index" >
										<view class="item" :class="item.isSelect==index?(an.answer?'yes':'no'):''" @click="chooseItem(index,an,item)">
											<view  style="flex:1;width:300rpx;"><text class="zm">{{handleZm(index)}}</text>. {{an.name}}</view>
											<view class="icon" v-if="item.isSelect==index">
												<image v-if="an.answer" src="/static/sec1.png" mode=""></image>
												<image v-else src="/static/error.png" mode=""></image>
											</view>
										</view>
									</block>
								</view>
							</view>
						</swiper-item>
						<!-- 看词选义 -->
						<swiper-item class="swiper-list" v-if="item.type==2">
							<view class="swiper-item">
								<view class="question">
									<view class="t">{{item.wordStr}}</view>
									<view class="yb" @click.stop="spell(item)">{{item.ukSoundmark}}
										<image src="/static/lb.png"></image>
									</view>
								</view>
								<view class="answer">
									<block v-for="(an,index) in item.wordList" :key="index" >
										<view class="item" :class="item.isSelect==index?(an.answer?'yes':'no'):''" @click="chooseItem(index,an,item)">
											<view class="as"><text class="zm">{{handleZm(index)}}</text>. {{an.name}}</view>
											<view class="icon" v-if="item.isSelect==index">
												<image v-if="an.answer" src="/static/sec1.png" mode=""></image>
												<image v-else src="/static/error.png" mode=""></image>
											</view>
										</view>
									</block>
								</view>
							</view>
						</swiper-item>
						<!-- 单词填空 -->
						<swiper-item class="swiper-list" v-if="item.type==4">
							<view class="swiper-item tk">
								<view class="q-box">
									<view class="tk-question" :class="item.inp==1?'y':(item.inp==2?'n':'')">
										<text v-for="(w,i) in item.inpAll" :key="i">{{w}}</text>
										<text class="wz" v-for="(num,i) in (item.name.length-item.inpAll.length)" :key="i"></text>
										<view class="d_flex_c cz" @click="reset(item)"><u-icon name="reload" size="15" color="#999"></u-icon>重置</view>	
									</view>
									<view class="tk-mean">
										<text>{{item.title}}</text>
									</view>
								</view>
								<view class="tk-answer">
									<view :class="a.checked?'item ac':'item'" v-for="(a,i) in item.opt" :key="i"
										@click="inputItem(a,item)">{{a.value}}</view>
								</view>
							</view>
						</swiper-item>
					</block>
				</swiper>
			</view>
			<view class="no-data" v-else-if="list.length==0&&noData">
				<u-empty mode="list" text="暂无复习数据" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" :is-mask-click="false" :safe-area="false" :mask-background-color="'rgba(0,0,0,0)'">
			<view class="pop-con" @touchstart="touchstart" @touchmove="touchmove">
				<view class="explain" :style="{height:height}">
					<Explain :detail="detail" :id="curId" @updateData="getDetail"></Explain>
				</view>
				<view class="btn-box">
					<view class="btn" @click="next">下一题</view>
				</view>
				<!-- <view class="explain" @click="toExplain">查看解析</view> -->
			</view>
		</uni-popup>
		<uni-popup ref="next" type="center">
			<view class="pop-cen">
				<view class="tip">
					真棒！已完成复习单词，是否继续复习？
				</view>
				<view class="btn-box">
					<view class="btn" @click="toIndex">休息一下</view>
					<view class="btn ac" @click="updateWord">我要继续</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Explain from './explain1.vue';
  import {handleExampleSentence} from "@/util/bizUtil";

  export default {
		components:{
			Explain
		},
		data() {
			return {
				error: -1,
				list: [],
				wordIds: [],
				current: 0,
				type: '', //1.普通复习 2.错题复习
				noData:false,
				innerAudioContext:'',
				curId:'',
				detail:'',
				initY:0,
				height:'200rpx',
			};
		},
		onLoad(e) {
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.autoplay = true;
			this.innerAudioContext.onError(res => {
				console.log(res.errMsg);
				console.log(res.errCode);
			});
			this.type = e.type || ''
			this.getData();
		},
		onShow() {
			if(uni.getStorageSync('lxCurrent')===0||uni.getStorageSync('lxCurrent')){
				let lxCur=uni.getStorageSync('lxCurrent');
				if(lxCur<this.list.length-1){
					this.current++
				}else{
					this.$refs.next.open();
				}
				uni.removeStorageSync('lxCurrent')
			}
		},
		methods: {
			touchstart(e){
				this.initY = e.touches[0].pageY;
			},
			touchmove(e){
				let lastY = e.touches[0].pageY;
				console.log(lastY)
				console.log(this.initY)
				if (lastY - this.initY< -20) {
					this.height="calc(100vh - 310rpx)"
				}else if(lastY - this.initY > 20){
					this.height="200rpx"
				}
			},
			subAnswer() {
				this.$refs.popup.open()
			},
			openPop() {
				this.$refs.next.open()
			},
			closeCen() {
				this.$refs.next.close()
				this.$refs.popup.close()
			},
			getData() {
				this.$http.get1('/api/client/word/review').then(res => {
					if (res.code == 200) {
						this.wordIds = res.data;
						let list = this.wordIds.map((item, i) => {
							let obj = {}
							obj.id = item;
							obj.index = i;
							obj.type = Math.round(Math.random() * 2 + 2);
							return obj;
						})
						this.getAllList(list);
					}
				})
			},
			getQuestion() {
				this.$http.post('api/client/word/cnDictionQuestion', this.wordIds).then(res => {
					if (res.code == 200) {
						this.list = res.data;
					}
				})
			},
			dealList(list) {
				let all = [];
				return new Promise((resolve, reject) => {
					list.forEach((e, i) => {
						all.push({
							id: e,
							index: i,
							type: Math.round(Math.random() * 2 + 2),
						});
					});

					resolve(all);
				});
			},
			getAllList(list) {
				uni.showLoading()
				let type2 = list.filter((it) => it.type == 2).map((it) => it.id);
				let type3 = list.filter((it) => it.type == 3).map((it) => it.id);
				let type4 = list.filter((it) => it.type == 4).map((it) => it.id);
				const p2 = (list) => {
					return new Promise((resolve, reject) => {
						this.$http.post('api/client/word/cnDictionQuestion', list).then(res => {
							let arryNew = [];
							if (res.code == 200 && res.data) {
								res.data.map((item, index) => {
									arryNew.push(
										Object.assign({}, item, {
											select: null,
											isSelect: -1,
											isAnswer:false,
											validity: null,
											error: null,
										})
									);
								});
								resolve(arryNew);
							}
						})
					});
				};

				const p3 = (list) => {
					return new Promise((resolve, reject) => {
						this.$http.post('api/client/word/enDictionQuestion', list).then(res => {
							let arryNew = [];
							if (res.code == 200 && res.data) {
								res.data.map((item, index) => {
									arryNew.push(
										Object.assign({}, item, {
											select: null,
											isSelect: -1,
											isAnswer:false,
											validity: null,
											error: null,
										})
									);
								});
								resolve(arryNew);
							}
						})
					});
				};

				const p4 = (list) => {
					return new Promise((resolve, reject) => {
						this.$http.post('api/client/word/wordDetailByIds', list).then(res => {
							let arryNew = [];
							if (res.code == 200 && res.data) {
								res.data.map((item, index) => {
									let _opt = this.getSort(item.name);
									let _title = JSON.parse(item.wordExplain)[0] && JSON.parse(
										item.wordExplain)[0].chinExplain;
									arryNew.push(
										Object.assign({}, item, {
											inp: "",
											inpAll: [],
											title: _title,
											opt: _opt,
											len: false,
											type: 4,
										})
									);
								});
								resolve(arryNew);
							}
						})
					});
				};
				Promise.all([p2(type2), p3(type3), p4(type4)])
					.then((res) => {
						this.sortList([...res[0], ...res[1], ...res[2]]);
					})
					.finally(() => {
						uni.hideLoading();
					});
			},
			sortList(list) {
				if(list.length==0){
					this.noData=true;
				}
				if (list.length <= 1) {
					this.list = list;
					return false;
				}
				var length = list.length,
					randomIndex,
					temp;
				while (length) {
					randomIndex = Math.floor(Math.random() * length--);
					temp = list[randomIndex];
					list[randomIndex] = list[length];
					list[length] = temp;
				}
				this.list = list;
				this.$forceUpdate();
				console.log(this.list);
			},
			getSort(words) {
				return words
					.split("")
					.sort(() => {
						return parseInt(Math.random() * (3 - 1 + 1) + 1, 10) - 2;
					})
					.map((v, i) => {
						return {
							id: i,
							value: v,
							checked: false,
						};
					});
			},
			/**
			// 选择答案 a-所选答案  item-当前题目
			*/
			chooseItem(i, a, item) {
				console.log(item);
				if (item.isSelect != -1) {
					return;
				}
				item.isAnswer = true;
				item.isSelect = i;
				this.$refs.popup.open();
				this.curId=item.wordId;
				this.getDetail();
				// if (a.answer) {
				// 	this.$refs.popup.open();
				// } else {
				// 	setTimeout(() => {
				// 		uni.navigateTo({
				// 			url: '/pages/test/explain?id=' + item.wordId + '&type=4'
				// 		})
				// 	}, 1500)
				// }
				this.markWord(item.wordId,a.answer)
			},
			inputItem(a, item) {
				if (!a.checked) {
					a.checked = true;
					item.inpAll.push(a.value);
				}
				if (item.inpAll.length == item.name.length) {
					this.curId=item.id;
					this.getDetail();
					if (item.inpAll.join('') == item.name) {
						this.$refs.popup.open();
						item.inp = 1;
					} else {
						item.inp = 2;
						this.$refs.popup.open();
						// setTimeout(() => {
						// 	uni.navigateTo({
						// 		url: '/pages/test/explain?id=' + item.id + '&type=4&current=' + this
						// 			.current
						// 	})
						// }, 1500)
					}
					this.updateWordStatus(item);
					// this.markWord(item.id,a.answer)
				}
			},
			//标记单词
			markWord(id,answer){
				this.$http.get1('api/client/word/signWord',{
					wordId:id,
					source:1,
					answer:answer?true:false,
					// date:new Date(),
				}).then(res=>{
					console.log(res);
				})
			},
			updateWordStatus(item) {
				this.$http.get1('api/client/word/signWord', {
					wordId: item.id,
					source: 1,
					answer: item.inp == 1 ? true : false
				})
			},
			// 查看解析
			toExplain() {
				uni.navigateTo({
					url: '/pagesA/pages/test/explain?id=' + this.list[this.current].wordId + '&type=4'
				})
			},
			//下一题
			next() {
				if (this.current < this.list.length - 1) {
					this.current++;
					this.$refs.popup.close();
					this.height='200rpx'
				} else {
					this.$refs.next.open();
				}
			},
			changeCurrent(e) {
				this.current = e.detail.current;
			},
			toIndex() {
				uni.navigateBack();
			},
			//拼读
			spell(item) {
				console.log(item)
				let that = this;
				this.$http
					.gettts('api/client/word/tts', {
						wordStr: item.wordStr,
						langType: 'en'
					})
					.then(res => {
						const fs = wx.getFileSystemManager();
						const basePath = `${wx.env.USER_DATA_PATH}/audio`;
						const audioPath = `${basePath}/${new Date().getTime()}.mp3`;
						let hasFolder = true;
						try {
							fs.accessSync(basePath);
						} catch (e) {
							hasFolder = false;
						}
						// 没有则先创建audio文件夹
						if (!hasFolder) {
							fs.mkdir({
								dirPath: basePath
							});
						}
						fs.writeFile({
							filePath: audioPath,
							data: res,
							encoding: 'binary',
							success: res => {
								that.innerAudioContext.src = audioPath;
								that.innerAudioContext.onPlay(() => {
									console.log('开始播放');
								});
							}
						});
					});
			},
			reset(item){
				item.inpAll=[];
				item.opt.map(val=>{
					val.checked=false;	
				})
			},
			getDetail() {
				this.$http.get1('/api/client/word/wordDetailById', {
					id: this.curId
				}).then(res => {
					if (res.code == 200) {
						this.detail = handleExampleSentence(res.data)
					}
				})
			},
			updateWord(){
				this.current=0;
				this.getQuestion();
				this.closeCen();
			},
		}
	}
</script>

<style lang="scss">
	.navbar {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		font-size: 22rpx;
		color: #333333;
		text-align: center;
		height: 96rpx;
		background: #F9FBFF;
		box-shadow: 0rpx 4rpx 8rpx 2rpx rgba(42, 65, 152, 0.05);
		line-height: 96rpx;
		position: fixed;
		z-index: 9;

		text {
			color: #5480F8;
			margin: 0 8rpx;
		}
	}

	.content {
		min-height: 100vh;
		padding-top: 120rpx;
		background-color: #F2F3F8;

		.swiper-box {
			height: calc(100vh - 180rpx);
			background-color: #F2F3F8;
			padding: 0;
			box-sizing: border-box;

			.swiper-list {
				height: 100%;
				padding:0 32rpx;
				box-sizing: border-box;
			}
		}
	}

	.swiper-item {
		background-color: #fff;
		padding: 32rpx;
		height:100%;
		border-radius: 20rpx;
		.question {
			min-height: 300rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			
			.t {
				font-size: 60rpx;
				font-weight: 800;
				color: #333333;
				margin-bottom: 30rpx;
				&.t1{
					font-size: 36rpx;
				}
			}
			.yb {
				position: relative;
				top: 300;
				font-size: 28rpx;
				color: #575A64;
				font-weight: 400;
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					margin-left: 30rpx;
					width: 32rpx;
					height: 32rpx;
				}
			}
			.tip {
				font-size: 28rpx;
				font-weight: 400;
				color: #575A64;

				image {
					width: 32rpx;
					height: 32rpx;
					margin-left: 40rpx;
				}
			}
		}

		.answer {
			.item {
				width: 100%;
				height: 120rpx;
				background: #FFFFFF;
				border-radius: 20rpx 20rpx 20rpx 20rpx;
				opacity: 1;
				border: 2rpx solid #E4E5EC;
				display: flex;
				align-items: center;
				padding: 0 28rpx;
				box-sizing: border-box;
				margin-bottom: 30rpx;
				justify-content: space-between;
				.as{
					display: -webkit-box;
					word-break: break-all;
					text-overflow:ellipsis;
					overflow: hidden;
					white-space: pre-line;
					-webkit-box-orient: vertical;
					-webkit-line-clamp:3;
				}
				&.yes{
					border: 1rpx solid #20CE7C;
					background: #F5FBF6;
				}
				&.no{
					background: #FFF8F8;
					border: 1rpx solid #FF7474;
				}
				.icon{
					width:40rpx;
					height: 40rpx;
				}
			}
			.zm{
				font-size: 36rpx;
			}
		}
	}
	.tk{
		.q-box{
				height: 300rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}
			.tk-question{
				text-align: center;
				margin-bottom: 40rpx;
				font-size: 60rpx;
				font-weight: 400;
				color: #575A64;
				display: flex;
				justify-content: center;
				align-items: center;
				&.y{
					color: #20CE7C;
				}
				&.n{
					color: #FF7474;
				}
				.wz{
					width: 40rpx;
					border-bottom: 4rpx solid #333333;
					height: 50rpx;
					display: inline-block;
					margin: 0 4rpx;
				}
				.cz{
					margin-left: 20rpx;
					font-size: 28rpx;
					color: #999;
				}
			}
			.tk-mean{
				text-align: center;
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
			}
			.tk-answer{
				display: grid;
				justify-content: space-between;
				grid-template-columns: repeat(auto-fill, 140rpx);
				grid-gap: 20rpx;
				.item{
					width: 140rpx;
					height: 120rpx;
					background: #FFFFFF;
					border-radius: 20rpx;
					border: 1rpx solid #E4E5EC;
					text-align: center;
					line-height: 120rpx;
					font-size: 40rpx;
					color: #333333;
					&.ac{
						background: #5480F8;
						color: #fff;
					}
				}
			}
		
	}
	.pop-con {
		width: 100%;
		background-color: #fff;
		padding: 30rpx 0;
		box-sizing: border-box;
		transition: all 600ms;
		border-radius: 20rpx 20rpx 0 0;

		.tip {
			font-size: 24rpx;
			color: #20CE7C;
			text-align: center;
		}

		.btn-box{
			height: 140rpx;
			border-top: 1rpx solid #eaeaea;
			padding:0 30rpx;
			box-sizing: border-box;
		}
		.btn{
			width: 680rpx;
			height: 90rpx;
			background: #5480F8;
			border-radius: 46rpx;
			text-align: center;
			line-height: 90rpx;
			color: #fff;
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;
			margin: 20rpx auto 30rpx;
		}
		.explain{
			transition: all 800ms;
			font-size: 24rpx;
			overflow: hidden;
			color: #5480F8;
			text-align: center;
		}
	}

	.pop-cen {
		width: 590rpx;
		background: #FCFDFF;
		border-radius: 20rpx;
		padding: 30rpx 40rpx 40rpx;
		box-sizing: border-box;

		.tip {
			margin: 40rpx 0;
			font-size: 32rpx;
			font-weight: 500;
			color: #333333;
		}

		.btn-box {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.btn {
				width: 240rpx;
				height: 90rpx;
				border-radius: 46rpx;
				border: 2rpx solid #5480F8;
				text-align: center;
				line-height: 90rpx;
				font-size: 32rpx;
				font-weight: 500;
				color: #5480F8;

				&.ac {
					background-color: #5480F8;
					color: #fff;
				}
			}
		}
	}
</style>